#!/bin/sh

# 2023-04-24 PR #3542 / PR #3549 context:
# "systemd-network" "RasPiOS" have files with the client wifi info within them,
# those can be parsed for the ssid without needing the related service running
# first.
# "Netplan systemd" "NetworkManager" need to be running to be able to parse for
# the ssid, from the generated config file for "Netplan systemd" and from the
# running environment for "NetworkManager".
# "iiab-wifi-test.service" acts as a bit of a traffic cop keeping the ordering
# of the services more deterministic when active and tries to catch a channel
# mismatch between client wifi's current setting and what is contained within
# hostapd.conf early in the boot process.

IFACE={{ discovered_wireless_iface }}
NETPLAN=0
SSID=""
# when we get here br0 should be available and dbus wpa_supplicant was started if enabled. Some
# of the backends that use wpa_supplicant should be active based on the Before= After= lines in
# the iiab-wifi-test.service unit file.
# https://github.com/iiab/iiab/pull/3542#issuecomment-1519647266

echo "iiab-test-wifi called"
echo "running pid $$"

# covers systemd-networkd
if [ -f /etc/wpa_supplicant/wpa_supplicant-$IFACE.conf ]; then
    echo "systemd-network"
    SSID=$(grep ssid /etc/wpa_supplicant/wpa_supplicant-$IFACE.conf | awk -F = '{print $2}' | sed -r s/\"// | sed -r s/\"//)
fi

# covers stock raspbian
if [ -f /etc/wpa_supplicant/wpa_supplicant.conf ] && [ -n "$(pgrep dhcpcd)" ]; then
    echo "RasPiOS"
    SSID=$(grep ssid /etc/wpa_supplicant/wpa_supplicant.conf | awk -F = '{print $2}' | sed -r s/\"// | sed -r s/\"//)
fi

# https://bugs.launchpad.net/ubuntu/+source/linux-firmware/+bug/1862760
# https://bugs.launchpad.net/netplan/+bug/1951586
# WiFi country code progress on arm64 OS's discussed on #3078
# covers netplan systemd use on server with bug workarounds
if [ -f /run/netplan/wpa-$IFACE.conf ]; then
    NETPLAN=1
    echo "Netplan systemd"
    SSID=$(grep ssid /run/netplan/wpa-$IFACE.conf | awk -F = '{print $2}' | sed -r s/\"// | sed -r s/\"//)
    REG_DOM=$(grep country /run/netplan/wpa-$IFACE.conf | awk -F = '{ print $2 }')
    if [ -z "$REG_DOM" ]; then
        NETPLAN=2
        echo "cover netplan wifi client lack of country= setting to {{ host_country_code }}"
        sed -i "s|ctrl_interface=/run/wpa_supplicant|&\ncountry={{ host_country_code }}|" /run/netplan/wpa-$IFACE.conf
    else
        echo "set hostapd wifi country to $REG_DOM"
        if [ -f /etc/hostapd/hostapd.conf.iiab ]; then
            sed -i "s|^country.*|country_code=$REG_DOM|" /etc/hostapd/hostapd.conf.iiab
            cp /etc/hostapd/hostapd.conf.iiab /etc/hostapd/hostapd.conf
        fi
    fi
fi

# NetworkManager
if [ -z "$SSID" ] && [ -n "$(pgrep NetworkManager)" ]; then
    echo "NetworkManager"
    sleep 15
    SSID=$(iw $IFACE info | grep ssid | awk '{print $2}' )
fi
echo "ssid is $SSID"

if [ -z "$SSID" ]; then
    echo "Couldn't find an UPSTREAM SSID in files like wpa_supplicant.conf -- so exiting."
    echo "CLARIF: This is normal when UPSTREAM WIFI is not active, as there would be no"
    echo "UPSTREAM SSID to extract, e.g. if 'wifi_up_down: False'"
    if [ $NETPLAN -gt 0 ]; then
       echo "Netplan1"
    fi
    exit 0
fi

if [ $NETPLAN -gt 0 ]; then
    echo "Netplan2 sleep 10"
    sleep 10
    wifi_processes=$(ps -A | grep wpa_supplicant | wc -l)
    if [ $wifi_processes -eq 1 ]; then
        # This is more of a netplan workaround should go away.
        echo "Problem - Now Starting netplan wifi"
        NETPLAN=2
    else
        echo "Not Restarting netplan wifi sleep 20"
        sleep 20
    fi
    # This one handles the changing of the country code from above
    if [ $NETPLAN -eq 2 ]; then
        echo "Restarting netplan-wpa-$IFACE sleep 20"
        /bin/systemctl --no-block restart netplan-wpa-$IFACE.service
        sleep 20
    fi
fi
sleep 10
wpa_cli -i $IFACE scan > /dev/null
sleep 2
FREQ=$(wpa_cli -i $IFACE scan_results | grep "$SSID" | awk '{print $2}')
for result in $FREQ; do
    echo "frequency is $result for $SSID"
    if [ "$result" -lt 2485 ] && [ "$result" -gt 2407 ]; then
        FREQ2=$result
        break
    else
        echo "channel $result is 5Ghz - ignoring"
    fi
done

echo "Using $FREQ2 for $SSID"

if [ -z "$FREQ2" ]; then
    echo "Couldn't find frequency to use exiting"
    if [ $NETPLAN -gt 0 ]; then
        echo "Netplan3"
    fi
    exit 0
fi

CHAN=$((FREQ2 - 2407))
CHAN=$((CHAN / 5))
echo "channel is $CHAN for $SSID"
HOSTAPD=$(grep channel /etc/hostapd/hostapd.conf | awk -F = '{print $2}')
echo "Hostapd set for $HOSTAPD"
if [ "$CHAN" -ne "$HOSTAPD" ]; then
    echo "Editing Hostapd for channel $CHAN"
    cp /etc/hostapd/hostapd.conf.iiab /etc/hostapd/hostapd.conf
    sed -i -e "s/^channel.*/channel=$CHAN/" /etc/hostapd/hostapd.conf
    /bin/systemctl --no-block restart hostapd
    echo "Restarted hostapd"
fi
